package com.lagou.zk;

import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author Cao Dun
 * @Date 2021/3/23 22:01
 * @Version 1.0
 * @Description
 */
public class Test {

    private static Connection connection;
    private static PutGetCfg putGetCfg;
    public static void main(String[] args) throws Exception {
        //1.获取zk的客户端
        putGetCfg = new PutGetCfg();
        ZkClient zkClient = putGetCfg.getZkClient();
        //2.发布数据连接池信息到zk集群
        putGetCfg.putCfg("druid.properties");
        CountDownLatch countDownLatch = new CountDownLatch(1);;

        //3.获取数据的连接
        connection = DruidUtils.getConnection();
        if(connection != null){
            System.out.println("连接数据成功。。。");
        }

        //4.创建线程模拟客户端修改数据库连接池信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //睡眠3s
                    Thread.sleep(3000);
                    //修改数据库连接池信息
                    putGetCfg.putCfg("druid.properties2");
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //4.监听节点的变化
        zkClient.subscribeDataChanges(PutGetCfg.POOL_PATH,new DbPoolIZkDataListener(putGetCfg,connection,countDownLatch));

        //5.啥都不做等待节点变化
        countDownLatch.await();

        //6.线程唤醒重新读取mysql连接池信息
        connection = DruidUtils.getConnection();
        if(connection != null){
            System.out.println("连接数据成功。。。");
        }



    }
}
